from typing import List, Dict, Any
from mcp.server import Server
from mcp.types import TextContent
from adb.client import ADBClient, Device


class DeviceHandlers:
    """设备相关请求处理器"""
    
    def __init__(self, server: Server):
        self.server = server
        self.adb_client = ADBClient()
        self._register_handlers()
    
    def _register_handlers(self):
        """注册MCP处理器"""
        
        @self.server.list_tools()
        async def list_tools():
            """列出可用的工具"""
            return [
                {
                    "name": "list_devices",
                    "description": "列出连接的Android设备",
                    "inputSchema": {
                        "type": "object",
                        "properties": {},
                        "required": []
                    }
                },
                {
                    "name": "get_device_info",
                    "description": "获取指定设备的详细信息",
                    "inputSchema": {
                        "type": "object",
                        "properties": {
                            "device_id": {
                                "type": "string",
                                "description": "设备ID"
                            }
                        },
                        "required": ["device_id"]
                    }
                },
                {
                    "name": "check_device_status",
                    "description": "检查设备连接状态",
                    "inputSchema": {
                        "type": "object",
                        "properties": {
                            "device_id": {
                                "type": "string",
                                "description": "设备ID"
                            }
                        },
                        "required": ["device_id"]
                    }
                }
            ]
        
        @self.server.call_tool()
        async def call_tool(name: str, arguments: Dict[str, Any]):
            """调用工具"""
            if name == "list_devices":
                return await self._handle_list_devices()
            elif name == "get_device_info":
                device_id = arguments.get("device_id")
                if not device_id:
                    raise ValueError("device_id参数是必需的")
                return await self._handle_get_device_info(device_id)
            elif name == "check_device_status":
                device_id = arguments.get("device_id")
                if not device_id:
                    raise ValueError("device_id参数是必需的")
                return await self._handle_check_device_status(device_id)
            else:
                raise ValueError(f"未知的工具: {name}")
    
    async def _handle_list_devices(self) -> List[Dict[str, Any]]:
        """处理设备列表请求"""
        try:
            devices = self.adb_client.list_devices()
            
            result = []
            for device in devices:
                result.append({
                    "device_id": device.device_id,
                    "status": device.status,
                    "product": device.product,
                    "model": device.model,
                    "transport_id": device.transport_id
                })
            
            return [
                TextContent(
                    type="text",
                    text=f"找到 {len(devices)} 个设备:\n" + 
                         "\n".join([f"- {d.device_id} ({d.status})" for d in devices])
                )
            ]
            
        except Exception as e:
            return [
                TextContent(
                    type="text",
                    text=f"获取设备列表失败: {str(e)}"
                )
            ]
    
    async def _handle_get_device_info(self, device_id: str) -> List[Dict[str, Any]]:
        """处理设备信息请求"""
        try:
            info = self.adb_client.get_device_info(device_id)
            
            info_text = f"设备 {device_id} 的详细信息:\n"
            for key, value in info.items():
                if key == 'properties':
                    info_text += f"- {key}: [系统属性]\n"
                else:
                    info_text += f"- {key}: {value}\n"
            
            return [
                TextContent(
                    type="text",
                    text=info_text
                )
            ]
            
        except Exception as e:
            return [
                TextContent(
                    type="text",
                    text=f"获取设备信息失败: {str(e)}"
                )
            ]
    
    async def _handle_check_device_status(self, device_id: str) -> List[Dict[str, Any]]:
        """处理设备状态检查请求"""
        try:
            is_online = self.adb_client.check_device_status(device_id)
            status = "在线" if is_online else "离线"
            
            return [
                TextContent(
                    type="text",
                    text=f"设备 {device_id} 状态: {status}"
                )
            ]
            
        except Exception as e:
            return [
                TextContent(
                    type="text",
                    text=f"检查设备状态失败: {str(e)}"
                )
            ]
